package vip.wangwenhao.sso.service.impl;

import org.springframework.context.annotation.Primary;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import vip.wangwenhao.autoconfigure.pojo.UserDetailsPojo;
import vip.wangwenhao.autoconfigure.utils.DateUtils;
import vip.wangwenhao.sso.entity.*;
import vip.wangwenhao.sso.mapper.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author wangwnehao
 */
@Component("userDetailsService")
@Primary
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private UserRoleMapper userRoleMapper;
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private PermissionMapper permissionMapper;
    @Resource
    private RolePermissionMapper rolePermissionMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserDetails loadUserByUsername(final String login) {
        String username = login.toLowerCase();
        User user = userMapper.selectByUsername(login);
        if (user == null) {
            throw new UsernameNotFoundException("User " + username + " was not found in the database");
        }
        //获取用户的所有权限并且SpringSecurity需要的集合
        Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        UserRole userRoleQuery = UserRole.builder().userId(user.getId()).build();
        List<UserRole> userRoles = userRoleMapper.query(userRoleQuery);
        for (UserRole userRole : userRoles) {
            //添加角色
            Long roleId = userRole.getRoleId();
            Role role = roleMapper.selectByPrimaryKey(roleId);
            GrantedAuthority roleGrantedAuthority = new SimpleGrantedAuthority(role.getRoleName());
            grantedAuthorities.add(roleGrantedAuthority);
            //添加权限
            RolePermission rolePermissionQuery = RolePermission.builder().roleId(roleId).build();
            List<RolePermission> rolePermissions = rolePermissionMapper.query(rolePermissionQuery);

            for (RolePermission rolePermission : rolePermissions) {
                Long permissionId = rolePermission.getPermissionId();
                Permission permission = permissionMapper.selectByPrimaryKey(permissionId);
                GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission.getPermissionName());
                grantedAuthorities.add(grantedAuthority);
            }
        }

        // 可用性 :true:可用 false:不可用
        boolean enabled = !user.getDisabled();
        // 有效性 :true:凭证有效 false:凭证无效
        boolean credentialsNonExpired = DateUtils.isExpired(user.getLastUpdatePassword());
        // 锁定性 :true:未锁定 false:已锁定
        boolean accountNonLocked = !user.getLocked();
        //返回一个SpringSecurity需要的用户对象
        UserDetailsPojo userDetailsPojo = new UserDetailsPojo(
                user.getUsername(),
                user.getPassword(),
                enabled,
                // 过期性 :true:没过期 false:过期
                // 账户永不过期
                true,
                credentialsNonExpired,
                accountNonLocked,
                grantedAuthorities);
        userDetailsPojo.setIteration(user.getIteration());
        userDetailsPojo.setSalt(user.getSalt());
        userDetailsPojo.setId(user.getId());
        return userDetailsPojo;
    }
}